import { treeselect as menuTreeselect, roleMenuTreeselectByOSType } from '@/api/system/menu'
import { changeRoleStatus, delRole, deptTreeSelect, getRole, listRole } from '@/api/system/role'
import { router } from '@/router'
import { addDateRange, formatDate } from '@/utils/common'
import { useDicts } from '@/utils/dict'
import { downloadFile } from '@/utils/http'
import { message } from '@/utils/message'
import type { PaginationProps } from '@pureadmin/table'
import { useGlobal } from '@pureadmin/utils'
import { type DateModelType, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, toRefs } from 'vue'

export function useRole() {
  const { $config } = useGlobal<GlobalPropertiesApi>()
  const data = reactive({
    form: {
      roleId: undefined,
      roleName: undefined,
      roleKey: undefined,
      roleSort: 0,
      status: '0',
      menuIds: [],
      deptIds: [],
      menuCheckStrictly: true,
      deptCheckStrictly: true,
      remark: undefined,
    },
    queryParams: {
      roleName: undefined,
      roleKey: undefined,
      status: undefined,
      osTypes: [0, $config.OSType],
    },
  })
  const { form, queryParams } = toRefs(data)
  const { sys_normal_disable } = useDicts('sys_normal_disable')
  const formDialogVisible = ref(false)
  const scopeFormDialogVisible = ref(false)

  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSelection = true
  const checkedKeys = ref([])
  const roleId = ref(0)
  const title = ref('')
  const dataList = ref([])
  const loading = ref(true)
  const dateRange = ref<DateModelType>(null)
  const menuOptions = ref([])
  const deptOptions = ref([])
  const menuRef: any = ref(null)
  const deptRef: any = ref(null)
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: 55,
      align: 'left',
      hide: ({ checkList }) => !checkList.includes('勾选列'),
    },
    {
      label: '序号',
      type: 'index',
      width: 70,
      hide: ({ checkList }) => !checkList.includes('序号列'),
    },
    {
      label: '角色编号',
      prop: 'roleId',
      minWidth: 100,
    },
    {
      label: '角色名称',
      prop: 'roleName',
      minWidth: 150,
    },
    {
      label: '权限字符',
      prop: 'roleKey',
      minWidth: 150,
    },
    {
      label: '显示顺序',
      prop: 'roleSort',
      minWidth: 100,
    },
    {
      label: '状态',
      prop: 'status',
      minWidth: 130,
      cellRenderer: (scope) => {
        return (
          <el-switch
            v-model={scope.row.status}
            active-value={'0'}
            inactive-value={'1'}
            onChange={() => handleStatusChange(scope.row)}
          ></el-switch>
        )
      },
    },
    {
      label: '创建时间',
      minWidth: 180,
      prop: 'createTime',
      formatter: ({ createTime }) => formatDate(createTime),
    },
    {
      label: '操作',
      fixed: 'right',
      width: 180,
      slot: 'operation',
    },
  ]

  /** 查询列表 */
  async function onSearch() {
    loading.value = true
    const params = {
      ...queryParams.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const { rows, total } = await listRole(addDateRange(params, dateRange.value))
    dataList.value = rows
    pagination.total = total
    loading.value = false
  }

  /** 查询菜单树结构 */
  function getMenuTreeselect() {
    const { osTypes } = queryParams.value
    menuTreeselect({ osTypes }).then((response: any) => {
      menuOptions.value = response.data
    })
  }

  /** 根据角色ID查询菜单树结构 */
  function getRoleMenuTreeselect(roleId) {
    const { osTypes } = queryParams.value
    return roleMenuTreeselectByOSType(roleId, osTypes).then((response: any) => {
      menuOptions.value = response.data.menus
      return response
    })
  }

  /** 重置新增的表单  */
  function reset() {
    form.value = {
      roleId: undefined,
      roleName: undefined,
      roleKey: undefined,
      roleSort: 0,
      status: '0',
      menuIds: [],
      deptIds: [],
      menuCheckStrictly: true,
      deptCheckStrictly: true,
      remark: undefined,
    }
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    getMenuTreeselect()
    title.value = '添加角色'
    checkedKeys.value = []
    formDialogVisible.value = true
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const roleId = row.roleId || ids.value
    const roleMenu = getRoleMenuTreeselect(roleId)
    getRole(roleId).then((response: any) => {
      form.value = response.data
      form.value.roleSort = Number(form.value.roleSort)
      formDialogVisible.value = true
      roleMenu.then((res) => {
        checkedKeys.value = res.data.checkedKeys
      })
      title.value = '修改角色'
    })
  }

  /** 根据角色ID查询部门树结构 */
  function getDeptTree(roleId) {
    return deptTreeSelect(roleId).then((response: any) => {
      deptOptions.value = response.data.depts
      return response
    })
  }

  /** 分配数据权限操作 */
  function handleDataScope(row) {
    const deptTreeSelect = getDeptTree(row.roleId)
    getRole(row.roleId).then((response: any) => {
      form.value = response.data
      scopeFormDialogVisible.value = true
      deptTreeSelect.then((res) => {
        checkedKeys.value = res.data.checkedKeys
      })
      title.value = '分配数据权限'
    })
  }

  /** 分配用户 */
  function handleAuthUser(roleId: number) {
    router.push({ name: 'AuthUser', params: { roleId } })
  }

  /** 导出按钮操作 */
  function handleExport() {
    downloadFile(
      'system/role/export',
      {
        ...queryParams.value,
      },
      `角色管理.xlsx`
    )
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const dictIds = row.roleId || ids.value
    ElMessageBox.confirm('数据一经删除不可恢复，请再次确认！', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await delRole(dictIds)
      message('删除成功', { type: 'success' })
      onSearch()
    })
  }

  /** 角色状态修改 */
  function handleStatusChange(row) {
    const text = row.status === '0' ? '启用' : '停用'
    ElMessageBox.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
      .then(function () {
        return changeRoleStatus(row.roleId, row.status)
      })
      .then(() => {
        message(text + '成功', { type: 'success' })
      })
      .catch(function () {
        row.status = row.status === '0' ? '1' : '0'
      })
  }

  /** 改变多选项 */
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.roleId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 改变分页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  /** 改变当前分页 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    dateRange.value = null
    onSearch()
  }

  onMounted(() => {
    onSearch()
  })

  return {
    form,
    title,
    roleId,
    loading,
    columns,
    deptRef,
    menuRef,
    multiple,
    dataList,
    dateRange,
    pagination,
    checkedKeys,
    menuOptions,
    deptOptions,
    queryParams,
    showSelection,
    formDialogVisible,
    sys_normal_disable,
    scopeFormDialogVisible,
    onSearch,
    resetForm,
    handleAdd,
    handleUpdate,
    handleDelete,
    handleDataScope,
    handleAuthUser,
    handleExport,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
  }
}
